﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace EYangFramework.Common.BasicHelper
{
    public class TableObjectConvert
    {
        public DataTable ChangeToTable<T>(List<T> instance) where T : class, new()
        {
            DataTable dtResult = new DataTable();
            var propertys = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
            foreach (var property in propertys)
            {
                dtResult.Columns.Add(property.Name);
            }
            foreach (var t in instance)
            {
                DataRow row = dtResult.NewRow();
                foreach (var pro in propertys)
                {
                    row[pro.Name] = pro.GetValue(t);
                }
                dtResult.Rows.Add(row);
            }
            return dtResult;
        }
        /// <summary>
        /// DataTable转换为对象,需要转换为具体的类型,否则会报错,暂时只支持枚举数DateTime类型的转换
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dtSource"></param>
        /// <returns></returns>
        public List<T> ChangeToObject<T>(DataTable dtSource) where T : class, new()
        {
            List<T> list = new List<T>();
            foreach (DataRow row in dtSource.Rows)
            {
                T t = new T();
                foreach (DataColumn column in dtSource.Columns)
                {
                    var property = t.GetType().GetProperty(column.ColumnName);
                    if (property == null)
                    {
                        continue;
                    }
                    t.GetType().GetProperty(column.ColumnName).SetValue(t, ChangeStringToTargetType(row[column.ColumnName].ToString(), property.PropertyType));
                }
                list.Add(t);
            }
            return list;
        }

        private object ChangeStringToTargetType(string value, Type property)
        {
            if (property.IsEnum)
            {
                return Enum.Parse(property, value);
            }
            if (property == typeof(DateTime))
            {
                return DateTime.Parse(value);
            }
            return value;
        }
    }
}
